package com.example.init;

import cn.hutool.core.util.StrUtil;
import com.example.util.ConfigUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;

public class RedisUtil {
    private static RedissonClient client;

    static {
        client = getClient();
    }

    public static RedissonClient getClient() {
        if (client == null) {
            RedisConfig redisConfig = ConfigUtil.getConfig("redis", RedisConfig.class);
            Config config = new Config();
            //设置纯文本，默认使用org.nustaq.serialization.FSTCodec编码
            config.setCodec(StringCodec.INSTANCE);
            //根据配置
            config.useSingleServer()
                  .setAddress(String.format("redis://%s:%d", redisConfig.getHost(), redisConfig.getPort()))
                  .setPassword(redisConfig.getPassword())
                  .setDatabase(redisConfig.getDatabase());
            client = Redisson.create(config);
        }
        return client;
    }

    public static void shutdown() {
        if (client != null) {
            client.shutdown();
        }
    }

    public static void set(String key, String value) {
        client.getBucket(key).set(value);
    }

    public static String get(String key) {
        return (String)client.getBucket(key).get();
    }
}